import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// POST /api/comments - 创建新评论
export async function POST(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const body = await request.json();
    const userId = session.user.id;

    // 验证请求体
    if (!body.content || !body.content.trim()) {
      return NextResponse.json(
        { success: false, message: '评论内容不能为空' },
        { status: 400 }
      );
    }

    if (!body.projectId) {
      return NextResponse.json(
        { success: false, message: '项目ID不能为空' },
        { status: 400 }
      );
    }

    // 检查用户是否有权限访问该项目
    const projectUser = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId: body.projectId,
        },
      },
    });

    if (!projectUser) {
      return NextResponse.json(
        { success: false, message: '没有权限在此项目中评论' },
        { status: 403 }
      );
    }

    // 如果是回复评论，检查父评论是否存在
    if (body.parentId) {
      const parentComment = await prisma.comment.findUnique({
        where: { id: body.parentId },
        include: { user: true }
      });

      if (!parentComment) {
        return NextResponse.json(
          { success: false, message: '要回复的评论不存在' },
          { status: 404 }
        );
      }
    }

    // 创建评论
    const comment = await prisma.comment.create({
      data: {
        content: body.content.trim(),
        userId,
        projectId: body.projectId,
        taskId: body.taskId || null,
        parentId: body.parentId || null, // 支持回复
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
        parent: {
          select: {
            id: true,
            content: true,
            userId: true,
            user: {
              select: {
                id: true,
                name: true,
              }
            }
          }
        },
        replies: {
          select: {
            id: true
          }
        }
      },
    });

    // 如果是任务评论，创建活动记录
    if (body.taskId) {
      // 获取任务信息
      const task = await prisma.task.findUnique({
        where: { id: body.taskId },
        select: { title: true }
      });

      // 创建活动记录
      await prisma.activity.create({
        data: {
          type: body.parentId ? "COMMENT_REPLIED" : "COMMENT_ADDED",
          userId,
          projectId: body.projectId,
          entityId: body.taskId,
          data: {
            comment: body.content.trim(),
            taskId: body.taskId,
            taskTitle: task?.title || "未知任务",
            parentId: body.parentId || null
          }
        }
      });

      // 如果任务有指派人且不是当前用户，发送通知
      const task2 = await prisma.task.findUnique({
        where: { id: body.taskId }
      });

      if (task2?.assigneeId && task2.assigneeId !== userId) {
        await prisma.notification.create({
          data: {
            type: "TASK_COMMENT",
            title: body.parentId ? "评论回复" : "新评论",
            content: body.parentId 
              ? `有人回复了您负责的任务"${task?.title || '未知任务'}"的评论`
              : `有人在您负责的任务"${task?.title || '未知任务'}"上发表了评论`,
            recipients: {
              create: {
                userId: task2.assigneeId
              }
            }
          }
        });
      }
      
      // 如果是回复评论，通知被回复的用户（如果不是当前用户）
      if (body.parentId) {
        const parentComment = await prisma.comment.findUnique({
          where: { id: body.parentId },
          select: { userId: true }
        });
        
        if (parentComment && parentComment.userId !== userId) {
          await prisma.notification.create({
            data: {
              type: "COMMENT_REPLY",
              title: "评论回复",
              content: `有人回复了您在任务"${task?.title || '未知任务'}"中的评论`,
              recipients: {
                create: {
                  userId: parentComment.userId
                }
              }
            }
          });
        }
      }
    }

    return NextResponse.json(
      { success: true, data: comment },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('创建评论失败:', error);
    return NextResponse.json(
      { success: false, message: '创建评论失败', error: error.message },
      { status: 500 }
    );
  }
}

// GET /api/comments - 获取评论
export async function GET(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const searchParams = request.nextUrl.searchParams;
    const taskId = searchParams.get('taskId');
    const projectId = searchParams.get('projectId');
    const userId = session.user.id;

    // 必须提供任务ID或项目ID
    if (!taskId && !projectId) {
      return NextResponse.json(
        { success: false, message: '必须提供任务ID或项目ID' },
        { status: 400 }
      );
    }

    // 如果提供了项目ID，检查用户是否有权限访问该项目
    if (projectId) {
      const hasAccess = await prisma.projectUser.findUnique({
        where: {
          userId_projectId: {
            userId,
            projectId,
          },
        },
      });

      if (!hasAccess) {
        return NextResponse.json(
          { success: false, message: '没有权限访问此项目的评论' },
          { status: 403 }
        );
      }
    }

    // 构建查询条件
    const where: any = {};
    if (taskId) where.taskId = taskId;
    if (projectId) where.projectId = projectId;
    
    // 只获取顶级评论
    where.parentId = null;

    // 查询评论
    const comments = await prisma.comment.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
        replies: {
          include: {
            user: {
              select: {
                id: true,
                name: true,
                image: true,
              }
            }
          },
          orderBy: { createdAt: 'asc' }
        }
      },
      orderBy: { createdAt: 'asc' },
    });

    return NextResponse.json({ success: true, data: comments });
  } catch (error: any) {
    console.error('获取评论失败:', error);
    return NextResponse.json(
      { success: false, message: '获取评论失败', error: error.message },
      { status: 500 }
    );
  }
} 